<template>
	<a-modal title="新增BOM" :width="1500" :visible="visible" :maskClosable="false" :confirmLoading="confirmLoading"
		@ok="handleSubmit" @cancel="handleCancel">

		<a-spin :spinning="confirmLoading">
			<a-form :form="form">
				<a-row>

					<a-col :span="12" v-show="false">
						<a-form-item label="主键" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入主键"
								v-decorator="['bomId', { rules: [{ required: false, message: '请输入主键！' }] }]" />
						</a-form-item>
					</a-col>

					<a-col :span="12" v-show="false">
						<a-form-item label="sid" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入sid"
								v-decorator="['sid', { rules: [{ required: true, message: '请输入sid！' }] }]" />
						</a-form-item>
					</a-col>

					<a-col :span="24" v-show="true">
						<a-form-item label="BOM名称" :labelCol="labelColBlock" :wrapperCol="wrapperColBlock" has-feedback="">
							<a-input placeholder="请输入BOM名称"
								v-decorator="['bomName', { rules: [{ required: true, message: '请输入BOM名称！' }] }]" />
						</a-form-item>
					</a-col>

					<a-col :span="12" v-show="true">
						<a-form-item label="BOM编码" :span="12" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入BOM编码"
								v-decorator="['bomCode', { rules: [{ required: true, message: '请输入BOM编码！' }] }]" />
						</a-form-item>
					</a-col>

					<a-col :span="12" v-show="false">
						<a-form-item label="BOM类型" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入类型"
								v-decorator="['bomType', { rules: [{ required: true, message: '请输入类型！' }] }]" />
						</a-form-item>
					</a-col>

					<a-col :span="12">
						<a-form-item label="分类" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<!--              <a-input placeholder="请输入BOM分类" v-decorator="['bomClass', {rules: [{required: true, message: '请输入BOM分类！'}]}]"-->
							<!--                       v-show="false"/>-->
							<a-select placeholder="请输入BOM分类"
								v-decorator="['bomClass', { rules: [{ required: true, message: '请输入BOM分类！' }] }]">
								<a-select-option :value="value" v-for="{ value, label } in bomClassArray">
									{{ label }}
								</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-radio-group style="width: 100%;"
								v-decorator="['isDisable', { rules: [{ required: true, message: '请选择状态！' }] }]">
								<a-radio :value="1">
									正常
								</a-radio>
								<a-radio :value="2">
									停用
								</a-radio>
							</a-radio-group>
						</a-form-item>
					</a-col>
					<a-col :span="24" v-if="false">
						<a-form-item label="产出物" :labelCol="labelColBlock" :wrapperCol="wrapperColBlock" has-feedback="">
							<a-input placeholder="请输入产出物"
								v-decorator="['output', { rules: [{ required: false, message: '请输入产出物！' }] }]" v-if="false" />
							<a-button type="dashed" @click="$refs.emsMaterialIndex1.show()">
								{{ outputName }}
							</a-button>
						</a-form-item>
					</a-col>

					<a-col :span="24" v-show="true">
						<a-form-item label="图片" :labelCol="labelColBlock" :wrapperCol="wrapperColBlock" has-feedback="">
							<a-input placeholder="请输入图片" v-decorator="['image', { rules: [{ required: true, message: '请输入图片！' }] }]"
								v-show="false" />
							<fc-upload ref="fcUpload" :handle-file-list-string-change="handleFileListStringChange" />
							<!-- <CropperUpload
                @fcsuccess="fcsuccess"
                avatarText=""
              /> -->
						</a-form-item>
					</a-col>

					<!--        自身BOM Table组件   -->
					<a-col :span="24" v-show="true">
						<a-form-item :validate-status="bomSelfValidate.validateStatus" :help="bomSelfValidate.errorMsg">
							<!--        复杂的BOM Table组件   -->
							<a-button type="primary"
								@click="() => { this.bomIndexVisible = true; this.$refs.emsBomIndexCopy.show() }">
								复制BOM
							</a-button>
							<ems-bom-index1 v-if="bomType == 1" ref="emsBomIndexCopy" :ok="handleCopy" />
							<ems-bom-index1 v-else ref="emsBomIndexCopy" :ok="handleCopyZuhe" />
							<FCBomMaterialTable ref="bomMaterialTableSelf" :default-bom="bom" :isPermission="managerOrFinance()" />
						</a-form-item>
					</a-col>

					<!--    引入别的BOM    -->
					<a-col :span="24" v-show="bomType == 2">
						<a-form-item>
							<a-button type="primary" @click="() => { this.bomIndexVisible = true; this.$refs.emsBomIndex1.show() }">
								引入其它BOM
							</a-button>
							<ems-bom-index1 ref="emsBomIndex1" :ok="onBomSelected" />
						</a-form-item>
					</a-col>

					<!--        其它BOM Table组件   -->
					<a-col :span="24" v-show="true">
						<a-form-item v-for="(item, index) in otherBoms">
							<FCBomMaterialTable :ref="'bomMaterialTable' + index" :key="index"
								@delete="(key) => otherBoms.splice(key, 1)" :default-bom="item" :isPermission="managerOrFinance()" />
						</a-form-item>
					</a-col>

				</a-row>
			</a-form>
			<ems-material-index1 ref="emsMaterialIndex1" :on-row-selected="onEmsMaterialIndex1Selected" />
		</a-spin>
	</a-modal>
</template>

<script>
import { add } from '@/api/modular/main/emsbom/emsBomManage'
import { listFull as emsBomMaterialListFull } from '@/api/modular/main/emsbommaterial/emsBomMaterialManage'  //原本的bom
import { detailFull } from '@/api/modular/main/emsbom/emsBomManage.js'  //新的bom详情

import { page as materialPage } from '@/api/modular/main/emsmaterial/emsMaterialManage'
import emsBomIndex1 from './emsBomIndex1'
import FcUpload from '@/components/FCUpload/FcUpload'
import FCBomMaterialTable from '@/views/main/emsbom/FCBomMaterialTable'
import emsMaterialIndex1 from '../emsmaterial/emsMaterialIndex1'
// import {sysDictDataPage} from '@/api/modular/system/dictDataManage'
import { sysDictDataList } from '@/api/modular/main/emssysdictdata/emsDictDataManage'
import { DICT_TYPE_ID_FOR_BOM_CLASS } from '@/utils/util'

export default {
	components: {
		FCBomMaterialTable,
		FcUpload,
		emsBomIndex1,
		emsMaterialIndex1
	},
	data() {
		return {
			labelCol: {
				xs: { span: 24 },
				sm: { span: 6 }
			},
			wrapperCol: {
				xs: { span: 24 },
				sm: { span: 15 }
			},
			labelColBlock: {
				xs: { span: 24 },
				sm: { span: 3 }
			},
			wrapperColBlock: {
				xs: { span: 24 },
				sm: { span: 20 }
			},
			visible: false,
			confirmLoading: false,
			form: this.$form.createForm(this),
			formModel: {},
			bomIndexVisible: false,
			bomType: 1,
			//  table 组件
			bomClassArray: [],
			bom: {
				bomId: '',
				bomCode: '',
				bomName: '本次BOM',
				bomType: '',
				status: '',
				image: '',
				createTime: '',
				createUser: '',
				updateTime: '',
				updateUser: '',
				bomMaterials: [],
				otherBoms: [],
			},
			bomMaterial: {
				bomMaterialId: '',
				bomId: '',
				bomIdSource: '',
				bomMaterialSort: '',
				materialId: '',
				materialNumber: '',
				createTime: '',
				createUser: '',
				updateTime: '',
				updateUser: '',
			},
			bomSelfValidate: {},
			otherBoms: [],
			selfBoms: []
		}
	},
	computed: {
		outputName() {
			return this.formModel.outputObject ? this.formModel.outputObject.materialName : '选择产出物'
		}
	},
	methods: {
		fcsuccess(url) {
			this.form.setFieldsValue({ image: url })
		},
		// 打开弹框时候生成一个单号
		createOrderNumber() {
			var d = new Date()
			var year = d.getFullYear()
			var month = d.getMonth()
			month = month + 1 > 12 ? 1 : month + 1
			month = month > 9 ? month : "0" + month.toString()
			var day = d.getDate()
			day = day > 9 ? day : "0" + day.toString()
			var hour = d.getHours()
			hour = hour > 9 ? hour : "0" + hour.toString()
			var minute = d.getMinutes()
			minute = minute > 9 ? minute : "0" + minute.toString()
			var second = d.getSeconds()
			second = second > 9 ? second : "0" + second.toString()

			let num = parseInt(Math.random() * 100000).toString()
			// 如果随机数长度不够5位,则在后面补0,够5位为止
			for (let i = num.length; i < 5; i++) {
				num += '0'
			}

			// let header = this.type==this.ORDER_TYPE_ENUM.inOrder.id?'WDRK': this.type==this.ORDER_TYPE_ENUM.outOrder.id?'WDCK':''

			let scOrderNo = 'BOM' + year + month + day + hour + minute + second + num

			this.form.setFieldsValue({ bomCode: scOrderNo })
		},
		add(record) {
			this.visible = true
			let bomType = record
			this.bomType = bomType
			setTimeout(() => {
				this.fileList = []
				this.bom = {}
				this.bomMaterial = {}
				this.otherBoms = []
				this.selfBoms = []
				this.form.resetFields()
				this.form.setFieldsValue({ bomType, sid: 0, isDisable: 1 })
				this.createOrderNumber()
			}, 100)
			this.getBomClass()

		},
		handleSubmit() {
			this.getSelfBomMaterialValue()
			const { form: { validateFields } } = this
			// return
			this.confirmLoading = true
			validateFields((errors, values) => {
				// this.confirmLoading = false
				if (!errors) {
					values = Object.assign({ bomMaterials: this.selfBoms, otherBoms: this.otherBoms }, values)
					add(values).then((res) => {
						this.confirmLoading = false
						if (res.success) {
							this.$message.success('新增成功')
							this.handleCancel()
							this.$emit('ok', values)
						} else {
							this.$message.info('新增失败：' + res.message)
						}
					}).finally((res) => {
						this.confirmLoading = false
					})
				} else {
					this.confirmLoading = false
				}
			})
		},
		handleCancel() {
			this.visible = false
			this.form.resetFields()
			this.$refs.fcUpload.handleClear()
			this.bom = {
				bomId: '',
				bomCode: '',
				bomName: '本次BOM',
				bomType: '',
				status: '',
				image: '',
				createTime: '',
				createUser: '',
				updateTime: '',
				updateUser: '',
				bomMaterials: [],
				otherBoms: [],
				copyBoms: [],
			}
			this.otherBoms = []
		},

		// upload
		handleFileListStringChange(fileListString) {
			this.form.setFieldsValue({ image: fileListString })
		},
		onBomSelected(selectedBomArray) {
			// console.log(`selectedBomArray:${JSON.stringify(selectedBomArray)}`)
			// 新增其它BOM,生成表格控件。数据结构为 bom，其中还需要建立关联的原料数组。
			// 同时还需要处理该BOM引用了多个原料或别的BOM的情况
			// // 表格里面显示BOM中包含的原料列表
			// 不管是普通BOM，还是组合BOM。都将引用的BOM中的原料放进同一张表中
			// 构建BOM数据
			if (selectedBomArray.length == 0) {
				this.$message.error('没有选择BOM')
				return
			}
			if (selectedBomArray.length > 1) {
				this.$message.error('暂不支持多选BOM添加')
				return
			}
			if (selectedBomArray.length > 0) {
				let selectedBom = selectedBomArray[0]
				let bomId = selectedBom.bomId
				// emsBomMaterialListFull({bomId}).then(res => {
				//   let bomMaterials = res.data
				//   // 构建BOM Bean
				//   selectedBom.bomMaterials = bomMaterials
				//   this.otherBoms.push(selectedBom)
				// })
				detailFull({ bomId }).then(res => {
					let bomMaterials = res.data.bomMaterials
					let otherBoms = res.data.otherBoms
					// 构建BOM Bean
					console.log('bom', res.data)
					console.log('otherBoms', otherBoms)
					// 构建BOM Bean
					selectedBom.bomMaterials = bomMaterials
					// this.bom = selectedBom
					this.otherBoms = [selectedBom, ...otherBoms]
				})
			}
		},
		handleCopy(selectedBomArray) {
			// console.log(`selectedBomArray:${JSON.stringify(selectedBomArray)}`)
			// 新增其它BOM,生成表格控件。数据结构为 bom，其中还需要建立关联的原料数组。
			// 同时还需要处理该BOM引用了多个原料或别的BOM的情况
			// // 表格里面显示BOM中包含的原料列表
			// 不管是普通BOM，还是组合BOM。都将引用的BOM中的原料放进同一张表中
			// 构建BOM数据
			if (selectedBomArray.length == 0) return this.$message.error('没有选择BOM')
			if (selectedBomArray.length > 1) return this.$message.error('暂不支持多选BOM添加')
			if (selectedBomArray.length > 0) {
				let selectedBom = selectedBomArray[0]
				let bomId = selectedBom.bomId
				detailFull({ bomId }).then(res => {
					let bomMaterials = res.data.bomMaterials
					let otherBoms = []
					res.data.otherBoms && res.data.otherBoms.length ? (res.data.otherBoms.forEach(item => {
						item.bomMaterials.forEach(innerItem => {
							otherBoms.push(innerItem)
						})
					})) : []
					// 构建BOM Bean
					console.log('bom', bomMaterials)
					// 构建BOM Bean
					selectedBom.bomMaterials = [...bomMaterials, ...otherBoms]
					this.bom = selectedBom
					// this.otherBoms = otherBoms
				})
			}
		},

		handleCopyZuhe(selectedBomArray) {
			console.log('6666666666666666666666666666')
			// console.log(`selectedBomArray:${JSON.stringify(selectedBomArray)}`)
			// 新增其它BOM,生成表格控件。数据结构为 bom，其中还需要建立关联的原料数组。
			// 同时还需要处理该BOM引用了多个原料或别的BOM的情况
			// // 表格里面显示BOM中包含的原料列表
			// 不管是普通BOM，还是组合BOM。都将引用的BOM中的原料放进同一张表中
			// 构建BOM数据
			if (selectedBomArray.length == 0) return this.$message.error('没有选择BOM')
			if (selectedBomArray.length > 1) return this.$message.error('暂不支持多选BOM添加')
			if (selectedBomArray.length > 0) {
				let selectedBom = selectedBomArray[0]
				let bomId = selectedBom.bomId
				detailFull({ bomId }).then(res => {
					let bomMaterials = res.data.bomMaterials
					let otherBoms = res.data.otherBoms
					// 构建BOM Bean
					// res.data.otherBoms&&res.data.otherBoms.length ? (res.data.otherBoms.forEach(item=>{
					//   item.bomMaterials.forEach(innerItem=>{
					//     otherBoms.push(innerItem)
					//   })
					// })) : []
					// 构建BOM Bean


					// 构建BOM Bean
					selectedBom.bomMaterials = bomMaterials
					this.bom = selectedBom
					// this.otherBoms = otherBoms
					console.log('bom', this.bom)
					console.log('other', otherBoms)
				})
			}
		},
		getSelfBomMaterialValue() {
			let tableValue = this.$refs.bomMaterialTableSelf.getTableValue()
			this.selfBoms = tableValue

			if (tableValue && tableValue.length > 0) {
				this.bomSelfValidate = {
					validateStatus: 'success',
					errorMsg: null,
				}
			} else {
				this.bomSelfValidate = {
					validateStatus: 'error',
					errorMsg: '物料清单不能为空',
				}
			}

			this.getBomTableValue()
		},
		getBomTableValue() {
			// bomMaterialTable
			for (let i = 0; i < this.otherBoms.length; i++) {
				let $refTable = this.$refs['bomMaterialTable' + i][0]
				this.otherBoms[i] = $refTable.getBom()
			}
			// for (const refsKey in this.$refs) {
			//   if (refsKey.startsWith('bomMaterialTable')) {
			//     let $refTable = this.$refs[refsKey]
			//     this.otherBoms.push($refTable.getTableValue())
			//   }
			// }
		},
		handleEmsMaterialIndex1Show() {
			this.$refs.emsMaterialIndex1.show()
		},
		onEmsMaterialIndex1Selected(materialRow) {
			// console.log(`选择了原料:id=${materialRow.materialId}, code=${materialRow.materialCode}, name=${materialRow.materialName}`)
			let { materialId, materialName, materialCode, materialType, costPrice } = materialRow
			this.form.setFieldsValue({ output: materialId })
			this.formModel = Object.assign({}, this.formModel, { output: materialId, outputObject: materialRow })
		},
		getBomClass() {
			sysDictDataList({ typeId: DICT_TYPE_ID_FOR_BOM_CLASS, pageSize: 999 }).then((res) => {
				let dictDataList = res.data
				let bomClassArray = dictDataList.map((dictData) => {
					return {
						value: dictData.id,
						label: dictData.value
					}
				})
				this.bomClassArray = bomClassArray
			})
		},
		onChangeByBomClass(value, option) {
			this.form.setFieldsValue({ bomClass: value })
		}
	}
}
</script>
